package com.party.course.controller;

/**
 * @author: zhaoyongke
 * @create: 2025-07-30 22:40
 * @description: TransparentQueryController
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hbga.xunpay.Xunpay;
import com.hbga.xunpay.XunpayClient;
import com.hbga.xunpay.exception.XunpayException;
import com.hbga.xunpay.model.ChannelTransparentQueryReqModel;
import com.hbga.xunpay.request.ChannelTransparentQueryRequest;
import com.hbga.xunpay.response.ChannelTransparentQueryResponse;
import com.party.common.core.domain.AjaxResult;
import com.party.course.domain.RealNameInfo;
import com.party.course.service.IRealNameInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

/**
 * 透传查询控制器
 */
@RestController
@RequestMapping("/transparent")
public class TransparentQueryController {


    @Autowired
    private IRealNameInfoService realNameInfoService;


    /**
     * 透传查询接口
     * @return 查询结果
     */
    @GetMapping("/query")
    public AjaxResult queryTransparent(RealNameInfo   realNameInfo) {

        String id = realNameInfo.getId();
        RealNameInfo realNameInfoquery = realNameInfoService.getById(id);

        try {
            // 配置支付参数（根据实际环境配置）
            Xunpay.mchNo = "M1752112514"; // 商户号
            Xunpay.appId = "686f1d82e4b02e1c8b4b5935"; // 应用ID
            //秘钥
            Xunpay.apiKey= "fPqfOo0sVJ31uvWZPH3iRvnNIkJDeW0bajMWaU7lJPvXNlA2RgI4E3TA68qstVd1YXeMYqH8zTra460UItPDcVZ8Kk6iPR1AgvpBQCSqIOa9rCsGeQ1vHi35jWXRPeTe";

            XunpayClient xunpayClient = new XunpayClient();
            ChannelTransparentQueryRequest request = new ChannelTransparentQueryRequest();
            ChannelTransparentQueryReqModel model = new ChannelTransparentQueryReqModel();
            // 设置查询参数
            model.setMchNo(Xunpay.mchNo);
            model.setAppId(Xunpay.appId);
            model.setTransparentId(realNameInfoquery.getTransparentId());
            request.setBizModel(model);
            // 执行查询请求
            ChannelTransparentQueryResponse response = xunpayClient.execute(request);
            // 验签
            boolean signCheck = response.checkSign(Xunpay.apiKey);
            System.out.println("验签结果： " + signCheck);

            // 处理响应结果
            if (response.isSuccess(Xunpay.apiKey)) {
                // 解析返回数据
                JSONObject result = parseQueryResponse(response);
                String applicationStatus = result.getString("applicationStatus");
                realNameInfoquery.setApplicationStatus(applicationStatus);
                realNameInfoService.updateById(realNameInfoquery);
                return AjaxResult.success("查询成功");
            } else {
                return AjaxResult.error("查询失败");
            }
        } catch (XunpayException e) {
            return AjaxResult.error();
        } catch (Exception e) {
            JSONObject errorResult = new JSONObject();
            errorResult.put("returnCode", "ERROR");
            errorResult.put("returnMsg", "系统异常: " + e.getMessage());
           return AjaxResult.success();
        }
    }


    public void queryTransparenttest(String  transparentId) {


        try {
            // 配置支付参数（根据实际环境配置）
            Xunpay.mchNo = "M1752112514"; // 商户号
            Xunpay.appId = "686f1d82e4b02e1c8b4b5935"; // 应用ID
            //秘钥
            Xunpay.apiKey= "fPqfOo0sVJ31uvWZPH3iRvnNIkJDeW0bajMWaU7lJPvXNlA2RgI4E3TA68qstVd1YXeMYqH8zTra460UItPDcVZ8Kk6iPR1AgvpBQCSqIOa9rCsGeQ1vHi35jWXRPeTe";

            XunpayClient xunpayClient = new XunpayClient();
            ChannelTransparentQueryRequest request = new ChannelTransparentQueryRequest();
            ChannelTransparentQueryReqModel model = new ChannelTransparentQueryReqModel();
            // 设置查询参数
            model.setMchNo(Xunpay.mchNo);
            model.setAppId(Xunpay.appId);
            model.setTransparentId(transparentId);
            request.setBizModel(model);
            // 执行查询请求
            ChannelTransparentQueryResponse response = xunpayClient.execute(request);
            // 验签
            boolean signCheck = response.checkSign(Xunpay.apiKey);
            System.out.println("验签结果： " + signCheck);
                // 解析返回数据
            JSONObject result = parseQueryResponse(response);

        } catch (XunpayException e) {

        } catch (Exception e) {
            JSONObject errorResult = new JSONObject();
            errorResult.put("returnCode", "ERROR");
            errorResult.put("returnMsg", "系统异常: " + e.getMessage());

        }
    }
    public static void main(String[] args) {

        TransparentQueryController transparentQueryController = new TransparentQueryController();
 transparentQueryController.queryTransparenttest("S1953608183637536769");
    }

    /**
     * 解析透传查询响应数据
     * @param response 查询响应
     * @return 解析后的结果
     */

    /**
     * 解析透传查询响应数据
     * @param response 查询响应
     * @return 解析后的结果
     */
    private JSONObject parseQueryResponse(ChannelTransparentQueryResponse response) {
        JSONObject result = new JSONObject();

        try {
            // 将response转换为JSON对象来处理
            JSONObject responseJson = JSON.parseObject(JSON.toJSONString(response));
            // 获取data对象
            JSONObject data = responseJson.getJSONObject("data");
            if (data != null) {
                // 基础信息
                result.put("transparentId", data.getString("transparentId"));
                result.put("mchNo", data.getString("mchNo"));
                result.put("appId", data.getString("appId"));
                result.put("ctCode", data.getString("ctCode"));
                result.put("mchTransparentNo", data.getString("mchTransparentNo"));
                result.put("state", data.getInteger("state"));
                result.put("createdAt", data.getLong("createdAt"));
                result.put("updatedAt", data.getLong("updatedAt"));

                // 解析res字段中的详细信息
                String resStr = data.getString("res");
                if (resStr != null && !resStr.isEmpty()) {
                    JSONObject resData = JSON.parseObject(resStr);

                    result.put("applicationStatus", resData.getString("applicationStatus"));
                    result.put("applicationNo", resData.getString("applicationNo"));
                    result.put("requestNo", resData.getString("requestNo"));
                    result.put("merchantNo", resData.getString("merchantNo"));
                    result.put("agreementSignUrl", resData.getString("agreementSignUrl"));
                    // 根据申请状态提供中文描述
//                    String statusDesc = getApplicationStatusDesc(resData.getString("applicationStatus"));
//                    result.put("applicationStatusDesc", statusDesc);
                }
            }

            result.put("returnCode", "SUCCESS");
            result.put("returnMsg", "查询成功");

        } catch (Exception e) {
            result.put("returnCode", "PARSE_ERROR");
            result.put("returnMsg", "解析响应数据失败: " + e.getMessage());
        }

        return result;
    }
    /**
     * 获取申请状态的中文描述
     * @param statusCode 状态码
     * @return 中文描述
     */
    private String getApplicationStatusDesc(String statusCode) {
        if (statusCode == null) {
            return "未知状态";
        }

        switch (statusCode) {
            case "REVIEWING":
                return "申请审核中";
            case "REVIEW_BACK":
                return "申请已驳回";
            case "BUSINESS_OPENING":
                return "业务开通中";
            case "COMPLETED":
                return "申请已完成";
            case "AGREEMENT_SIGNING":
                return "协议待签署";
            default:
                return statusCode;
        }
    }

    /**
     * 批量透传查询接口
     * @param transparentIds 透传ID列表
     * @return 查询结果列表
     */
//    @PostMapping("/query/batch")
//    public Object batchQueryTransparent(@RequestBody String[] transparentIds) {
//        JSONObject batchResult = new JSONObject();
//        batchResult.put("total", transparentIds.length);
//
//        JSONObject results = new JSONObject();
//        int successCount = 0;
//
//        for (String transparentId : transparentIds) {
//            try {
//                JSONObject singleResult = (JSONObject) queryTransparent(transparentId);
//                results.put(transparentId, singleResult);
//
//                if ("SUCCESS".equals(singleResult.getString("returnCode"))) {
//                    successCount++;
//                }
//            } catch (Exception e) {
//                JSONObject errorResult = new JSONObject();
//                errorResult.put("returnCode", "ERROR");
//                errorResult.put("returnMsg", "查询异常: " + e.getMessage());
//                results.put(transparentId, errorResult);
//            }
//        }
//
//        batchResult.put("success", successCount);
//        batchResult.put("failed", transparentIds.length - successCount);
//        batchResult.put("results", results);
//
//        return batchResult;
//    }
}
